package com.yksj.healthtalk.ui.home;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;

public class WithdrawingRegistrationFragment extends RootFragment implements
		OnClickListener {

	private TextView messageEt;
	private Button mSureBtn;
	private ImageView mImageView1;
	private ImageView mImageView2;
	private ImageView mImageView3;
	private String docterId;
	private PopupWindow mPopupWindow;
	public int CAMERA_REQUESTCODE = 0;
	private int PHOTO_PICKED_WITH_DATA = 1;
	private int MESSAGE = 2;
	private File storageFile;
	private ImageView mInfoHeadIv;
	private String[] paths = new String[3];
	private int imagePosition = 1;
	private String message = "";// 返回字符串
	private StringBuilder builder;
	private Intent intent;
	private CustomerInfoEntity infoEntity;// 列表参数
	private MyDoctorListFrament frament;
	private EditText payAcount;
	private EditText payAcountAgain;
	private EditText telephone;
	private String tel;
	private String account;
	private Bitmap bm;
	private MyDoctorCommonServiceActivity mDoctorCommonServiceActivity;
	private String order_id;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.withdrawing_registration, null);
		initWidget(v);
		initData(v);
		return v;
	}

	public static Fragment getInstance(CustomerInfoEntity mInfoEntity, String account, String tel,String order_id) {
		WithdrawingRegistrationFragment fragment = new WithdrawingRegistrationFragment();
		Bundle args = new Bundle();
		args.putParcelable("mInfoEntity", mInfoEntity);
		args.putString("account", account);
		args.putString("tel", tel);
		args.putString("order_id", order_id);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		mDoctorCommonServiceActivity = (MyDoctorCommonServiceActivity) activity;
		super.onAttach(activity);
	}

	private void initData(View v) {
		titleTextV.setText(R.string.withdrawing_registration);
		infoEntity = getArguments().getParcelable("mInfoEntity");
		account = getArguments().getString("account");
		tel = getArguments().getString("tel");
		order_id = getArguments().getString("order_id");
		docterId = infoEntity.getId();
		// 账号
		if (!TextUtils.isEmpty(account)) {
			payAcount.setText(account);
			payAcountAgain.setText(account);
		}

		// 电话号码
		if (tel != null && !TextUtils.isEmpty(tel.trim())) {
			telephone.setText(tel.trim());
		}
	}

	private void initWidget(View v) {
		initTitleView( v);
		titleLeftBtn.setOnClickListener(this);
		messageEt = (TextView) v.findViewById(R.id.message);
		mSureBtn = (Button) v.findViewById(R.id.sure);
		mImageView1 = (ImageView) v.findViewById(R.id.iv1);
		mImageView2 = (ImageView) v.findViewById(R.id.iv2);
		mImageView3 = (ImageView) v.findViewById(R.id.iv3);
		payAcount = (EditText) v.findViewById(R.id.pay_acount);
		payAcountAgain = (EditText) v.findViewById(R.id.pay_acount_again);
		telephone = (EditText) v.findViewById(R.id.telephone);
		initClickListener();
	}

	private void initClickListener() {
		// TODO Auto-generated method stub
		mSureBtn.setOnClickListener(this);
		mImageView1.setOnClickListener(this);
		mImageView2.setOnClickListener(this);
		mImageView3.setOnClickListener(this);
		messageEt.setOnClickListener(this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			mDoctorCommonServiceActivity.onBackPressed();
			break;
		case R.id.sure:
			WithdrawingRegistration();
			break;
		case R.id.iv1:
			mInfoHeadIv = mImageView1;
			showuploadPopWindow();
			break;
		case R.id.iv2:
			mInfoHeadIv = mImageView2;
			showuploadPopWindow();
			break;
		case R.id.iv3:
			mInfoHeadIv = mImageView3;
			showuploadPopWindow();
			break;
		case R.id.galleryadd:
			intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.cameraadd:
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			storageFile = StorageUtils.createCameraFile();
			if (storageFile == null) {
				ToastUtil.showShort(getActivity(), "记忆卡不可用");
				return;
			}
			Uri uri = Uri.fromFile(storageFile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intent, CAMERA_REQUESTCODE);
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.cancel:
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.message:
			intent = new Intent(getActivity(), WithdrawingMessageActivity.class);
			intent.putExtra("message", message);
			startActivityForResult(intent, MESSAGE);
			break;
		default:
			break;
		}
	}

	/**
	 * 分享弹出框
	 */
	public void showuploadPopWindow() {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		View view = inflater.inflate(R.layout.interest_image_add_action, null);
		View mainView = inflater.inflate(R.layout.interest_content, null);
		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
		}
		WheelUtils.setPopeWindow((Context) getActivity(), mainView,
				mPopupWindow);
		Button cameraAdd = (Button) view.findViewById(R.id.cameraadd);
		Button galleryAdd = (Button) view.findViewById(R.id.galleryadd);
		Button cancel = (Button) view.findViewById(R.id.cancel);
		TextView title = (TextView)view.findViewById(R.id.title);
		title.setVisibility(View.GONE);
		cameraAdd.setOnClickListener(this);
		galleryAdd.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	/**
	 * 退票
	 */
	private void WithdrawingRegistration() {
		String pay = payAcount.getText().toString().trim();
		String payAgain = payAcountAgain.getText().toString().trim();
		String tel = telephone.getText().toString().trim();
		String result = FriendUtil.inputVerify(message, pay, payAgain, tel,
				imagePosition);
		if (result != null) {
			SingleBtnFragmentDialog.showDefault(getChildFragmentManager(), result);
			return;
		}
		File[] files = new File[3];
		for (int i = 0; i < paths.length; i++) {
			if (paths[i] == null) {
				files[i] = null;
			} else {
				files[i] = new File(paths[i]);
			}
		}
			HttpRestClient.doHttpWithdrawingRegistration(order_id,SmartFoxClient.getSmartFoxClient().getUserId(), docterId, message, pay,tel, files[0], files[1], files[2],
					new JsonHttpResponseHandler(getActivity()) {
						@Override
						public void onSuccess(int statusCode,
								JSONObject response) {
								if (response.has("error_code")) {
									try {
										String str = response.getString("error_message");
										ToastUtil.showShort(getActivity(), str);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								} else {
									try {
										// {"message":"上传成功！","serviceStatusCode":"20","serviceStatus":"退号申请中"}
										if (response.has("message")) {
											infoEntity.setServiceStatusCode(response.getString("serviceStatusCode"));
											infoEntity.setServiceStatus(response.getString("serviceStatus"));
										}
										ToastUtil.showToastPanl(response.getString("message"));
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									getActivity().onBackPressed();
								}
							super.onSuccess(statusCode, response);
						}
						@Override
						public void onFinish() {
							if (bm != null) {
								bm.recycle();
							}
							super.onFinish();
						}
					});
		}
	/**
	 * 图像依次显示
	 * 
	 * @param imagePosition
	 */
	private void changeImageViewVisible(int imagePosition) {
		// TODO Auto-generated method stub
		ImageView[] ivs = { mImageView1, mImageView2, mImageView3 };

		for (int i = 0; i < imagePosition; i++) {
			ivs[i].setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAMERA_REQUESTCODE
				&& resultCode == Activity.RESULT_OK) {
			try{
				bm = BitmapUtils.decodeBitmap(storageFile.getAbsolutePath(), 900,
						900);
				File file = StorageUtils.createHeaderFile();
				StorageUtils.saveImageOnImagsDir(bm, file);
				paths[imagePosition - 1] = file.getAbsolutePath();
				mInfoHeadIv.setImageBitmap(bm);
				setImageVisible();
			}catch(Exception e){
			}
		} else if (requestCode == PHOTO_PICKED_WITH_DATA
				&& resultCode == Activity.RESULT_OK) {
			try{
				Bitmap photo = data.getParcelableExtra("data");
				File file = StorageUtils.createHeaderFile();
				StorageUtils.saveImageOnImagsDir(photo, file);
				paths[imagePosition - 1] = file.getAbsolutePath();
				mInfoHeadIv.setImageBitmap(photo);
				setImageVisible();
			}catch(Exception e){
			}
		} else if (requestCode == MESSAGE && resultCode == Activity.RESULT_OK) {
			if (data != null && data.hasExtra("message")) {
				message = data.getStringExtra("message");
				if (!message.equals("")) {
					builder = new StringBuilder();
					builder.append("退号原因").append("\n").append(message);
					SpannableStringBuilder style = new SpannableStringBuilder(
							builder.toString());
					style.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 4,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					style.setSpan(new ForegroundColorSpan(getResources()
							.getColor(R.color.tag_note)), 4, builder.toString()
							.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					messageEt.setText(style);
				} else {
					messageEt.setText(R.string.withdrawing_reason);
				}
			}
		}
	}

	private void setImageVisible() {
		if (mInfoHeadIv == mImageView1) {
			imagePosition = 2;
			changeImageViewVisible(imagePosition);
		} else if (mInfoHeadIv == mImageView2) {
			imagePosition = 3;
			changeImageViewVisible(imagePosition);
		} else if (mInfoHeadIv == mImageView3) {
		}
	}

}
